<script setup>
import {useRoute} from "vue-router";
import {onMounted, reactive, ref} from "vue";
import router from "@/router";
import {$ajax, apiUrl} from "@/utils/ajax";

const route = useRoute()
const form = ref()
const data = reactive({
  id: "",
  name: "",
  mobile: "",
  password: "",
  state: 1,
  pid: 0
})
const rule = reactive({
  name: [
    {required: true, message: '请输入代理名称', trigger: 'blur'},
    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
  ],
  mobile: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'},
    {pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,16}$/, message: '请输入6-16位数字和字母的组合', trigger: 'blur'}
  ]
})
const loading = ref(false)
const submitForm = (refs)=>{
  refs.validate(err=>{
    loading.value = err
    if(err){
      $ajax.post(`${apiUrl}admin/supplier/save`, data).then(()=>{
        loading.value = false
        router.replace({name: 'supplier'})
      }).catch(()=>loading.value = false)
    }
  })
}

onMounted(()=>{
  if(route.params.id){
    $ajax.get(`${apiUrl}admin/supplier/detail`, {params:{id: route.params.id}}).then(({data:{result:res}})=>{
      data.id = res.id
      data.name = res.name
      data.mobile = res.mobile
      data.state = res.state
      data.pid = res.pid
    })
  }
})
</script>

<template>
  <div class="breadcrumb">
    <el-breadcrumb>
      <el-breadcrumb-item :to="{name:'home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{name: 'supplier'}">代理商</el-breadcrumb-item>
      <el-breadcrumb-item>{{ route.params.id ? '编辑' : '新增' }}代理商</el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <el-form class="form-data" ref="form" :model="data" :rules="rule" label-width="100px" label-position="left" @keyup.enter="submitForm(form)">
    <el-form-item label="代理名称" prop="name">
      <el-input v-model="data.name" clearable/>
    </el-form-item>
    <el-form-item label="手机号" prop="mobile">
      <el-input v-model="data.mobile" clearable/>
    </el-form-item>
    <el-form-item label="密码" :prop="route.params.id?'':'password'">
      <el-input v-model="data.password" clearable/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" round class="edit-btn" @click="submitForm(form)" :loading="loading">提交</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">

</style>
